#include <Arduino.h>
#include "power.h"
#include "driver/adc.h"
#include "esp_adc_cal.h"

static esp_adc_cal_characteristics_t adc1_chars;

void powerInit()
{
    // 初始化电量检测ADC
    esp_err_t ret;
    analogSetPinAttenuation(BAT_PIN, ADC_2_5db);
    ret = esp_adc_cal_check_efuse(ESP_ADC_CAL_VAL_EFUSE_TP);
    if (ret == ESP_ERR_NOT_SUPPORTED)
    {
        //  Serial.println( "Calibration scheme not supported, skip software calibration");
    }
    else if (ret == ESP_ERR_INVALID_VERSION)
    {
        // Serial.println("eFuse not burnt, skip software calibration");
    }
    else if (ret == ESP_OK)
    {
        esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_2_5, ADC_WIDTH_BIT_13, 0, &adc1_chars);
    }
    else
    {
        //    Serial.println("Invalid arg");
    }

    // 初始化电源控制IO
    pinMode(POWER_S, INPUT_PULLUP);
    pinMode(POWER_C, OUTPUT);
    digitalWrite(POWER_C, LOW);
}

// 开机检测，检测长按1s开机
void checkPowerOn()
{
    delay(800);
    // if (!digitalRead(POWER_S))
    if(1)
    {
        powerOn();
        Serial.println("powerOn");
    }
    else
    {
        Serial.println("will restart");
        delay(1000);
        powerOff();
    }
}

float readBatVoltage()
{

    uint32_t temp = 0;
    for (size_t i = 0; i < 10; i++)
    {
        temp += analogRead(BAT_PIN);
        delay(1);
    }
    temp = esp_adc_cal_raw_to_voltage(temp / 10, &adc1_chars);

    // temp/20*(20+100)*Vref
    // Vref=1.1V
    // float voltage= 1.0*voltage/1000/20*(20+100);
    float voltage = 1.0 * temp / 2000 * 12;

    return voltage;
}

void powerOn()
{
    digitalWrite(POWER_C, HIGH);
}
void powerOff()
{
    digitalWrite(POWER_C, LOW);
    ESP.restart();
}